﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DSkin.Controls;
using System.Xml;
using System.Collections;

namespace DS.Controls
{
    public partial class DSTreeView : DSkinUserControl
    {
        public DSTreeView()
        {
            InitializeComponent();
            SetScrollBarStyle();
        }

        private void SetScrollBarStyle()
        {
            treeviewfolder.InnerScrollBar.ShowArrow = true;
            treeviewfolder.InnerScrollBar.BackColor = Color.Transparent;
            treeviewfolder.InnerScrollBar.Fillet = true;
            treeviewfolder.InnerScrollBar.Width = 10;
        }

        delegate void RunTaskDelegate();
        //delegate void SetProgressbarCallback(object sender, AioApp.Upload.ZipEventArgs e);

        List<string> UploadDirs = new List<string>();

        UploadConfig uploadConfig = new UploadConfig();

        private void Uploader_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 加载Uploader
        /// </summary>
        public void LoadUploader()
        {
            LoadDirs();
            GetUploadParams();
            this.Visible = true;
        }

        private void LoadDirs()
        {
            treeviewfolder.Nodes.Clear();
            TreeNode rootNode = new TreeNode("我的电脑",
                IconIndexes.MyComputer, IconIndexes.MyComputer);  //载入显示 选择显示

            //循环遍历计算机所有逻辑驱动器名称(盘符)
            foreach (string driver in Environment.GetLogicalDrives())
            //foreach (DriveInfo drive in drivers)
            {
                //实例化DriveInfo对象 命名空间System.IO
                var dir = new DriveInfo(driver);
                DSkinTreeViewNode tNode = new DSkinTreeViewNode();
                tNode.Text = dir.Name.Split(':')[0];
                tNode.Name = dir.Name;
                tNode.Tag = tNode.Name;
                //tNode.ImageIndex = IconIndexes.FixedDrive;         //获取结点显示图片
                //tNode.SelectedImageIndex = IconIndexes.FixedDrive; //选择显示图片
                treeviewfolder.Nodes.Add(tNode);                    //加载驱动节点
                tNode.Nodes.Add(new DSkinTreeViewNode());

                
            }


            string[] netFolder = SocketProject.NetUse.GetNetDir(@"\\CE_CLOUD_3\project_1");
            foreach (string folder in netFolder)
            {
                //实例化DriveInfo对象 命名空间System.IO
                
                

                DSkinTreeViewNode tNode = new DSkinTreeViewNode();
                tNode.Text = folder;
                tNode.Name = folder;
                tNode.Tag = tNode.Name;
                //tNode.ImageIndex = IconIndexes.FixedDrive;         //获取结点显示图片
                //tNode.SelectedImageIndex = IconIndexes.FixedDrive; //选择显示图片
                treeviewfolder.Nodes.Add(tNode);                    //加载驱动节点
                tNode.Nodes.Add(new DSkinTreeViewNode());


            }
            

            rootNode.Expand();
        }

        private void GetUploadParams()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            if (!path.EndsWith(@"\"))
                path += @"\";

            string configFile = path + "upload.xml";

            if (!File.Exists(configFile))
            {
                //MessageBox.Show("缺少服务器配置文件 请手动配置ip");
            }
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(configFile);

                //uploadConfig = Utils.XmlUtil.Deserialize(typeof(UploadConfig), doc.InnerXml) as UploadConfig;
                //if (uploadConfig.FtpPasswd.IndexOf("@") > -1)
                //{
                //    MessageBox.Show("xml配置中密码不能有@等特殊符号");
                //    return;
                //}
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            //ftpconfig.FtpHost = obj["ftpHost"].ToString();
            //ftpconfig.FtpPasswd = obj["ftpPasswd"].ToString();
            //ftpconfig.FtpUser = obj["ftpUser"].ToString();
            //ftpconfig.FtpPort = obj["ftpPort"].ToString();
            //webServiceUrl = obj["webServiceUrl"].ToString();
            //userID = obj["userID"].ToString();
        }

        private void dSkinTreeView1_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (treeviewfolder.SelectedNode.CheckState == CheckState.Unchecked && treeviewfolder.SelectedNode.Nodes.Count == 1)//前面添加了一个默认节点 点击的时候才加载后面的层
            {
                TreeViewItems.AddNode(treeviewfolder.SelectedNode);
            }
        }


        /// <summary>
        /// 自定义类TreeViewItems 调用其Add(TreeNode e)方法加载子目录
        /// </summary>
        /// <summary>
        /// 自定义类TreeViewItems 调用其Add(TreeNode e)方法加载子目录
        /// </summary>
        public static class TreeViewItems
        {
            public static void AddNode(DSkinTreeViewNode e)
            {
                //try..catch异常处理
                try
                {
                    //判断"我的电脑"Tag 上面加载的该结点没指定其路径
                    if (e.Text != "我的电脑")
                    {
                        e.Nodes.Clear();                               //清除空节点再加载子节点
                        DSkinTreeViewNode tNode = e;                            //获取选中\展开\折叠结点
                        string path = tNode.Name;                      //路径  

                        //获取"我的文档"路径
                        if (e.Text == "我的文档")
                        {
                            path = Environment.GetFolderPath           //获取计算机我的文档文件夹
                                (Environment.SpecialFolder.MyDocuments);
                        }

                        //获取指定目录中的子目录名称并加载结点
                        string[] dics = Directory.GetDirectories(path);
                        Array.Sort(dics, new FilesNameComparerClass());

                        foreach (string dic in dics)
                        {
                            DSkinTreeViewNode subNode = new DSkinTreeViewNode(); //实例化
                            subNode.Text = new DirectoryInfo(dic).Name;
                            subNode.Name = new DirectoryInfo(dic).FullName;               //完整目录
                            subNode.Tag = subNode.Name;

                            if (subNode.Text.Equals("images") || subNode.Text.Equals("Rescource"))
                            {
                                //排除treeview显示 资源里的images 和 Resource 文件夹
                                if (Directory.GetDirectories(subNode.Name).Length == 0)
                                return;
                            }

                            tNode.Nodes.Add(subNode);
                            subNode.Nodes.Add(new DSkinTreeViewNode());//叶子节点
                        }
                    }
                }
                catch (Exception msg)
                {
                    MessageBox.Show(msg.Message);                   //异常处理
                }
            }
        }

        /// <summary>
        /// IconIndexs类 对应ImageList中5张图片的序列
        /// </summary>
        public class IconIndexes
        {
            public const int MyComputer = 0;      //我的电脑
            public const int ClosedFolder = 1;    //文件夹关闭
            public const int OpenFolder = 2;      //文件夹打开
            public const int FixedDrive = 3;      //磁盘盘符
            public const int MyDocuments = 4;     //我的文档
        }
        [Serializable]
        public class UploadConfig
        {
            string ftpHost;

            public string FtpHost
            {
                get { return ftpHost; }
                set { ftpHost = value; }
            }
            string ftpUser;

            public string FtpUser
            {
                get { return ftpUser; }
                set { ftpUser = value; }
            }
            string ftpPasswd;

            public string FtpPasswd
            {
                get { return ftpPasswd; }
                set { ftpPasswd = value; }
            }
            string ftpPort;

            public string FtpPort
            {
                get { return ftpPort; }
                set { ftpPort = value; }
            }


        }

        ///<summary>
        ///主要用于文件名的比较。
        ///</summary>
        public class FilesNameComparerClass : IComparer
        {
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            ///<summary>
            ///比较两个字符串，如果含用数字，则数字按数字的大小来比较。
            ///</summary>
            ///<param name="x"></param>
            ///<param name="y"></param>
            ///<returns></returns>
            int IComparer.Compare(Object x, Object y)
            {
                if (x == null || y == null)
                    throw new ArgumentException("Parameters can't be null");
                string fileA = x as string;
                string fileB = y as string;
                char[] arr1 = fileA.ToCharArray();
                char[] arr2 = fileB.ToCharArray();
                int i = 0, j = 0;
                while (i < arr1.Length && j < arr2.Length)
                {
                    if (char.IsDigit(arr1[i]) && char.IsDigit(arr2[j]))
                    {
                        string s1 = "", s2 = "";
                        while (i < arr1.Length && char.IsDigit(arr1[i]))
                        {
                            s1 += arr1[i];
                            i++;
                        }
                        while (j < arr2.Length && char.IsDigit(arr2[j]))
                        {
                            s2 += arr2[j];
                            j++;
                        }

                        if (long.Parse(s1) > long.Parse(s2))
                        {
                            return 1;
                        }
                        if (long.Parse(s1) < long.Parse(s2))
                        {
                            return -1;
                        }
                    }
                    else
                    {
                        if (arr1[i] > arr2[j])
                        {
                            return 1;
                        }
                        if (arr1[i] < arr2[j])
                        {
                            return -1;
                        }
                        i++;
                        j++;
                    }
                }
                if (arr1.Length == arr2.Length)
                {
                    return 0;
                }
                else
                {
                    return arr1.Length > arr2.Length ? 1 : -1;
                }
                //            return string.Compare( fileA, fileB );
                //            return( (new CaseInsensitiveComparer()).Compare( y, x ) );
            }
        }

        public class CustomComparer : System.Collections.IComparer
        {
            public int Compare(object x, object y)
            {
                string s1 = (string)x;
                string s2 = (string)y;
                if (s1.Length > s2.Length) return 1;
                if (s1.Length < s2.Length) return -1;
                for (int i = 0; i < s1.Length; i++)
                {
                    if (s1[i] > s2[i]) return 1;
                    if (s1[i] < s2[i]) return -1;
                }
                return 0;
            }
        }



        private void dSkinTreeView1_DoubleClick(object sender, EventArgs e)
        {
            treeviewfolder.SelectedNode.NodesOpened = !treeviewfolder.SelectedNode.NodesOpened;
        }




        /// <summary>
        /// 查询TreeView下节点被checked的数目
        /// </summary>
        /// <param name="treev"></param>
        /// <returns></returns>
        private void GetTreeViewNodeChecked(DSkinTreeView treev)
        {
            //int k = 0;
            foreach (DSkinTreeViewNode item in treev.Nodes)
            {
                GetNodeChecked(item);
            }
            //return k;
        }
        /// <summary>
        /// 查询treeNode节点下有多少节点被选中（递归实现，不受级数限制）
        /// </summary>
        /// <param name="tv"></param>
        /// <returns></returns>
        private void GetNodeChecked(DSkinTreeViewNode tv)
        {
            if (tv.CheckState==CheckState.Checked)
            {
                if (null != tv.Name)
                    UploadDirs.Add(tv.Name.ToString());
            }
            foreach (DSkinTreeViewNode item in tv.Nodes)
            {
                GetNodeChecked(item);
            }
            //return x;
        }

    }
}
